// utils/request.js
import { API_BASE_URL } from './config.js';
import { getToken, clearUserInfo } from './auth.js';

const BASE_URL = API_BASE_URL;

export function request({ url, method = 'GET', data = {}, header = {}, showLoading = true, skipAuth = false }) {
  if (showLoading) {
    uni.showLoading({ title: '加载中...', mask: true });
  }
  
  return new Promise((resolve, reject) => {
    // 准备请求头
    const requestHeader = {
      'Content-Type': 'application/json',
      ...header
    };
    
    // 添加认证token（除非明确跳过）
    if (!skipAuth) {
      const token = getToken();
      if (token) {
        requestHeader['Authorization'] = token;
      }
    }
    
    uni.request({
      url: BASE_URL + url,
      method,
      data,
      header: requestHeader,
      success: (res) => {
        if (showLoading) uni.hideLoading();
        
        // 处理响应
        if (res.statusCode === 200) {
          resolve(res.data);
        } else if (res.statusCode === 401) {
          // 未授权，清除登录信息并跳转到登录页
          handleUnauthorized();
          reject({
            status: 401,
            message: '登录已过期，请重新登录',
            data: res.data
          });
        } else if (res.statusCode === 403) {
          // 权限不足
          uni.showToast({ 
            title: '权限不足', 
            icon: 'none' 
          });
          reject({
            status: 403,
            message: '权限不足',
            data: res.data
          });
        } else if (res.statusCode === 404) {
          // 资源不存在
          uni.showToast({ 
            title: '请求的资源不存在', 
            icon: 'none' 
          });
          reject({
            status: 404,
            message: '请求的资源不存在',
            data: res.data
          });
        } else if (res.statusCode >= 500) {
          // 服务器错误
          uni.showToast({ 
            title: '服务器错误，请稍后重试', 
            icon: 'none' 
          });
          reject({
            status: res.statusCode,
            message: '服务器错误',
            data: res.data
          });
        } else {
          // 其他错误
          const errorMessage = res.data?.message || `请求失败 (${res.statusCode})`;
          uni.showToast({ 
            title: errorMessage, 
            icon: 'none' 
          });
          reject({
            status: res.statusCode,
            message: errorMessage,
            data: res.data
          });
        }
      },
      fail: (err) => {
        if (showLoading) uni.hideLoading();
        
        console.error('请求失败:', err);
        
        // 网络错误处理
        let errorMessage = '网络连接失败';
        
        if (err.errMsg) {
          if (err.errMsg.includes('timeout')) {
            errorMessage = '请求超时，请检查网络连接';
          } else if (err.errMsg.includes('fail')) {
            errorMessage = '网络请求失败，请检查网络设置';
          }
        }
        
        uni.showToast({ 
          title: errorMessage, 
          icon: 'none' 
        });
        
        reject({
          status: 0,
          message: errorMessage,
          data: err
        });
      }
    });
  });
}

/**
 * 处理未授权情况
 */
function handleUnauthorized() {
  // 清除用户信息
  clearUserInfo();
  
  // 提示用户
  uni.showToast({
    title: '登录已过期，请重新登录',
    icon: 'none'
  });
  
  // 跳转到登录页
  setTimeout(() => {
    uni.reLaunch({
      url: '/pages/login/index'
    });
  }, 1500);
}

/**
 * GET请求
 */
export function get(url, params = {}, options = {}) {
  const queryString = Object.keys(params)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
    .join('&');
    
  const fullUrl = queryString ? `${url}?${queryString}` : url;
  
  return request({
    url: fullUrl,
    method: 'GET',
    ...options
  });
}

/**
 * POST请求
 */
export function post(url, data = {}, options = {}) {
  return request({
    url,
    method: 'POST',
    data,
    ...options
  });
}

/**
 * PUT请求
 */
export function put(url, data = {}, options = {}) {
  return request({
    url,
    method: 'PUT',
    data,
    ...options
  });
}

/**
 * DELETE请求
 */
export function del(url, options = {}) {
  return request({
    url,
    method: 'DELETE',
    ...options
  });
}

/**
 * 上传文件
 */
export function upload(url, filePath, name = 'file', formData = {}) {
  return new Promise((resolve, reject) => {
    uni.showLoading({ title: '上传中...', mask: true });
    
    const uploadTask = uni.uploadFile({
      url: BASE_URL + url,
      filePath,
      name,
      formData,
      header: {
        'Authorization': getToken()
      },
      success: (res) => {
        uni.hideLoading();
        
        if (res.statusCode === 200) {
          try {
            const data = JSON.parse(res.data);
            resolve(data);
          } catch (e) {
            reject({ message: '响应数据格式错误' });
          }
        } else {
          reject({ message: `上传失败 (${res.statusCode})` });
        }
      },
      fail: (err) => {
        uni.hideLoading();
        console.error('上传失败:', err);
        reject({ message: err.errMsg || '上传失败' });
      }
    });
    
    return uploadTask;
  });
}